package com.beemans.common.utils

import android.animation.Animator
import android.animation.ValueAnimator
import android.view.animation.AccelerateDecelerateInterpolator
import androidx.viewpager2.widget.ViewPager2

/**
 * @author tiamosu
 * @date 2021/9/16.
 *
 * 修改[ViewPager2]切换速度
 */
class ViewPager2Helper(private val viewPager2: ViewPager2) {

    /**
     * 保存前一个animatedValue
     */
    private var previousValue = 0

    /**
     * 设置当前Item
     *
     * @param item          下一个跳转的item
     * @param smoothScroll  是否进行平滑切换
     */
    fun setCurrentItem(item: Int, smoothScroll: Boolean = true) {
        viewPager2.setCurrentItem(item, smoothScroll)
    }

    /**
     * 设置当前Item
     *
     * @param item          下一个跳转的item
     * @param duration      scroll时长
     */
    fun setCurrentItem(item: Int, duration: Long) {
        previousValue = 0
        val currentItem = viewPager2.currentItem
        val pagePxWidth = viewPager2.width
        val pxToDrag = pagePxWidth * (item - currentItem)

        ValueAnimator.ofInt(0, pxToDrag).apply {
            addUpdateListener { animation: ValueAnimator ->
                val currentValue = animation.animatedValue as? Int ?: 0
                val currentPxToDrag = (currentValue - previousValue).toFloat()
                viewPager2.fakeDragBy(-currentPxToDrag)
                previousValue = currentValue
            }
            addListener(object : Animator.AnimatorListener {
                override fun onAnimationStart(animation: Animator) {
                    viewPager2.beginFakeDrag()
                }

                override fun onAnimationEnd(animation: Animator) {
                    viewPager2.endFakeDrag()
                }

                override fun onAnimationCancel(animation: Animator) {}
                override fun onAnimationRepeat(animation: Animator) {}
            })
            interpolator = AccelerateDecelerateInterpolator()
            this.duration = duration
            start()
        }
    }
}